﻿using System;
using System.Linq;
using System.Windows;

namespace Sinacor.Infra.UI.Controls.SmartClient.DataGrid
{
    internal static class DataGridColumnManager
    {
        #region Initialize
        public static void Initialize(Type columnType)
        {
            Microsoft.Windows.Controls.DataGridColumn.IsReadOnlyProperty.OverrideMetadata(columnType, new FrameworkPropertyMetadata(true));
        }
        #endregion

        #region Name
        /// <summary>
        /// Nome da coluna
        /// </summary>
        public static readonly DependencyProperty NameProperty = DependencyProperty.RegisterAttached("Name", typeof(string), typeof(DataGridColumnManager), new FrameworkPropertyMetadata(null));
        #endregion

        #region SortIndex
        /// <summary>
        /// Ordem que a coluna foi ordenada
        /// </summary>
        public static readonly DependencyPropertyKey SortIndexKey = DependencyProperty.RegisterAttachedReadOnly("SortIndex", typeof(int), typeof(DataGridColumnManager), new FrameworkPropertyMetadata(-1, null, CoerceSortIndex));
        public static readonly DependencyProperty SortIndexProperty = SortIndexKey.DependencyProperty;

        private static object CoerceSortIndex(DependencyObject d, object value)
        {
            IDataGridColumn column = (IDataGridColumn)d;

            if (column.DataGrid != null)
            {
                if (column.SortIndex == -1 && ((Microsoft.Windows.Controls.DataGridColumn)column).SortDirection != null)
                {
                    // Nova ordenação
                    value = (from IDataGridColumn c in column.DataGrid.Columns select c.SortIndex).Max() + 1;
                }
                else if (column.SortIndex > -1 && ((Microsoft.Windows.Controls.DataGridColumn)column).SortDirection == null)
                {
                    // Limpando ordenação
                    foreach (IDataGridColumn c in column.DataGrid.Columns)
                    {
                        if (c.SortIndex > column.SortIndex)
                        {
                            ((Microsoft.Windows.Controls.DataGridColumn)c).SetValue(DataGridColumnManager.SortIndexKey, c.SortIndex - 1);
                            break;
                        }
                    }

                    value = -1;
                }
                else
                {
                    // Invertendo ordem, mantem índice
                    value = column.SortIndex;
                }
            }
            else
            {
                value = -1;
            }

            return value;
        }
        #endregion

        #region HorizontalCellAlignment
        /// <summary>
        /// Alinhamento horizontal do conteúdo da célula
        /// </summary>
        public static readonly DependencyProperty HorizontalCellAlignmentProperty = DependencyProperty.RegisterAttached("HorizontalCellAlignment", typeof(HorizontalAlignment), typeof(DataGridColumnManager), new FrameworkPropertyMetadata(HorizontalAlignment.Left));
        #endregion

        #region VerticalCellAlignment
        /// <summary>
        /// Alinhamento vertical do conteúdo da célula
        /// </summary>
        public static readonly DependencyProperty VerticalCellAlignmentProperty = DependencyProperty.RegisterAttached("VerticalCellAlignment", typeof(VerticalAlignment), typeof(DataGridColumnManager), new FrameworkPropertyMetadata(VerticalAlignment.Center));
        #endregion

        #region CanUserChangeVisibility
        /// <summary>
        /// Indica se o usuário pode alterar a visibilidade da coluna
        /// </summary>
        public static readonly DependencyProperty CanUserChangeVisibilityProperty = DependencyProperty.RegisterAttached("CanUserChangeVisibility", typeof(bool), typeof(DataGridColumnManager), new FrameworkPropertyMetadata(true));

        private static void CoerceCanHideColumn(IDataGridColumn column)
        {
            if (column.DataGrid != null)
            {
                column.DataGrid.CoerceValue(SinacorDataGrid.CanHideColumnProperty);
            }
        }

        private static void CoerceChangeVisibilityColumns(IDataGridColumn column)
        {
            if (column.DataGrid != null)
            {
                column.DataGrid.CoerceValue(SinacorDataGrid.ChangeVisibilityColumnsProperty);
            }
        }
        #endregion

        #region Excel

        #region CanUserExportExcel
        /// <summary>
        /// Indica se a coluna permite ser exportada para Excel
        /// </summary>
        public static readonly DependencyProperty CanUserExportExcelProperty = DependencyProperty.RegisterAttached("CanUserExportExcel", typeof(bool), typeof(DataGridColumnManager), new FrameworkPropertyMetadata(true));

        private static void CoerceIsExportableExcel(IDataGridColumn column)
        {
            if (column.DataGrid != null)
            {
                column.DataGrid.CoerceValue(SinacorDataGrid.IsExportableExcelProperty);
            }
        }
        #endregion

        #endregion

        #region PropertyChanged
        public static void PropertyChanged(Microsoft.Windows.Controls.DataGridColumn column, DependencyPropertyChangedEventArgs e)
        {
            // SortDirection
            if (e.Property == Microsoft.Windows.Controls.DataGridColumn.SortDirectionProperty)
            {
                column.CoerceValue(SortIndexProperty);
            }
            // CanUserChangeVisibility
            else if (e.Property == CanUserChangeVisibilityProperty)
            {
                CoerceChangeVisibilityColumns((IDataGridColumn)column);
            }
            // Visibility
            else if (e.Property == Microsoft.Windows.Controls.DataGridColumn.VisibilityProperty)
            {
                CoerceCanHideColumn((IDataGridColumn)column);
            }
            // DisplayIndex
            else if (e.Property == Microsoft.Windows.Controls.DataGridColumn.DisplayIndexProperty)
            {
                CoerceChangeVisibilityColumns((IDataGridColumn)column);
            }
            // CanUserExportExcel
            else if (e.Property == CanUserExportExcelProperty)
            {
                CoerceIsExportableExcel((IDataGridColumn)column);
            }

			((IDataGridColumn)column).TriggerPropertyChanged(e.Property.Name);
        }
        #endregion
    }
}
